﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;

namespace Abc.Core.EventBus;

/// <summary>
/// 事件总线读取数据
/// </summary>
[JobDetail("job_EventBusReadDataJob", concurrent: false, "事件总线读取数据")]
//文档：26.1.5.6 作业触发器特性及自定义
[PeriodSeconds(5, TriggerId = "trigger_EventBusReadDataJob")]
public class EventBusReadDataJob : IJob
{
    private readonly ISqlSugarClient _db;
    private readonly IServiceScope _serviceScope;//高频定时任务
    public EventBusReadDataJob(ISqlSugarClient db)
    {
        _db = db;
    }


    public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
    {
        var option = AppEx.GetConfig<EventBusOptions>();
        //判断是否开启了事件总线
        if (option.IsEnableEventBus == false)
        {
            await Task.CompletedTask;
            return;
        }
        try
        {

#if DEBUG
            Console.WriteLine($" 从数据库读取 事件源存储的数据：{DateTimeOffset.Now:yyyy-MM-dd HH:mm:ss.fffff}");
#endif

            //验证待处理的事件队列，防止加载过多事件到内存中
            if (EventBusHelper.Instance.PendingEventSubscribeQueues.Count > 2000)
            {
                await Task.CompletedTask;
                return;
            }

            //判断是否有事件待处理
            var isEventSource = await _db.IsAnyAsync<SysEventSourceStorer>(o => o.State == EventSourceStorerState.未处理);
            if (isEventSource == false)
            {
                await Task.CompletedTask;
                return;
            }

            //这个地方要防止重复加入队列数据
            var datas = await _db.Queryable<SysEventSourceStorer>()
           .Where(o => o.State == EventSourceStorerState.未处理)
           .Take(500).ToListAsync(o => new SysEventSourceStorer()
           {
               Id = o.Id,
               ExtensionData = o.ExtensionData,
               EventId = o.EventId,
               Payload = o.Payload,
               State = o.State
           });
            foreach (var item in datas)
            {
                //判断队列中是否存在,如果存在跳过
                if (EventBusHelper.Instance.PendingEventSubscribeQueues.Any(o => o.Id == item.Id)) continue;
                //判断处理中的集合中是否存在,如果存在跳过
                if (EventBusHelper.Instance.ProcessingEventSubscribes.ContainsKey(item.Id)) continue;
                //新的事件数据加入队列中
                EventBusHelper.Instance.PendingEventSubscribeQueues.Enqueue(item);
            }

        }
        catch (Exception ex)
        {
            LogEx.Error(ex.ToStringEx());
        }
        finally
        {

        }

        await Task.CompletedTask;
    }
}
